package cn.hxth.dubbo.customer.shiro.filter;


import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;

public class KickoutSessionControlFilter extends AccessControlFilter {
private  String kickoutUrl = "/loginForm" ;
private Cache<Object, Object> cache ;
private SessionManager sessionManager ;
private  int maxSessionCount = 10 ;
private  boolean kickoutAfter = false ;
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		System.out.println("xia");
		Subject subject = super.getSubject(request, response);

		if(!subject.isAuthenticated()&& !subject.isRemembered()){
			return  true ;
		}
		Session session = subject.getSession();
		String mid = (String) subject.getPrincipal();
		System.out.println(mid);
		Deque<Serializable> allSessions = (Deque<Serializable>) this.cache.get(mid);
		if(allSessions==null){
			allSessions = new LinkedList<>() ;

		}
		if(!allSessions.contains(session.getId())){
		allSessions.add(session.getId()) ;
		this.cache.put(mid,allSessions) ;
		System.out.println(allSessions.size()) ;

		if(allSessions.size()>maxSessionCount&&session.getAttribute("kickout") ==null){
			Serializable kickoutId ;
			if(this.kickoutAfter){
				 kickoutId = allSessions.removeLast();
			}
			else{
				kickoutId  = allSessions.removeFirst() ;
			}

			Session kickoutSession = this.sessionManager.getSession(new DefaultSessionKey(kickoutId));
			kickoutSession.setAttribute("kickout",true);



		}
		this.cache.put(mid,allSessions) ;
		if(session.getAttribute("kickout")!=null){
			subject.logout();
			super.saveRequest(request);
			WebUtils.issueRedirect(request,response,this.kickoutUrl+ "?kickmsg=out");

			return false;
		}}
		return  true ;



	}

	public void setKickoutUrl(String kickoutUrl) {
		this.kickoutUrl = kickoutUrl;
	}


	public void setSessionManager(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}

	public void setMaxSessionCount(int maxSessionCount) {
		this.maxSessionCount = maxSessionCount;
	}

	public void setCacheManager(CacheManager cacheManager) {
		this.cache =cacheManager.getCache("kickout");
	}

	public void setKickoutAfter(boolean kickoutAfter) {
		this.kickoutAfter = kickoutAfter;
	}
}
